<?php
/**
 * Created by jinqiang on 2024/12/18 11:20.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Callback;


use App\Http\Models\Mysql\SsyPricingContractTable;
use App\Http\Models\Mysql\SsyPricingOrderTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListDetailsTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Repository\SzdptechRepository;

class ShujiaService
{
    //加工单同步
    public function processingSync($list)
    {
        //工厂信息
        if(!isset($list[0]['factory_name']) || empty($list[0]['factory_name'])){
            return ['code' => -1, 'msg' => '加工厂未设置'];
        }
        $factoryObj = (new SsyProcessingFactoryNameTable())->where('factory_name', $list[0]['factory_name'])
            ->orWhere('factory_name_jiancheng', $list[0]['factory_name'])->first();
        $factoryObj = !empty($factoryObj) ? $factoryObj->toArray() : [];
        if(empty($factoryObj)){
            return ['code' => -1, 'msg' => '加工厂不存在'];
        }
        $styleObj = (new StyleTable())->where('number', $list[0]['type_no'])->first(['brand_id']);
        $subjects = array_column(config("scm.subject"), null, 'brand_id');
        $factoryObj['source_factory_groups_id'] = $subjects[$styleObj->brand_id]['supplier_id'] ?? "";
        $brandName = $subjects[$styleObj->brand_id]['brand_name'] ?? "";
        $brandCode = $subjects[$styleObj->brand_id]['brand_code_s'] ?? "";
        //同步大货核价单
        if(!isset($list[0]['verify_price_number']) || empty($list[0]['verify_price_number'])){
            return ['code' => -1, 'msg' => '大货核价编码缺少'];
        }
        $this->addPricingOrder($list[0]['verify_price_number']);
        //同步合同信息
        if(!isset($list[0]['factory_contract_no']) || empty($list[0]['factory_contract_no'])){
            return ['code' => -1, 'msg' => '未填写工厂合同号'];
        }
        $addRes = $this->addPricingContract($factoryObj, $list[0]);
        if($addRes['code'] !== 0){
            return $addRes;
        }
        $createTime = date('Y-m-d H:i:s');
        foreach ($list as $item) {
            if(!$item['s_status']){
                return ['code' => -1, 'msg' => '加工单未审核不可同步'];
            }
            if(empty($item['num'])){
                continue;
            }
            $processingObj = (new SsyProcessingListTable())->where('processing_code', $item['processing_code'])->where('sku_code', $item['sku_code'])->first();
            if(empty($processingObj)){
                $data = [
                    'type_name' => trim($item['type_name']),
                    'type_no' => trim($item['type_no']),
                    'color_code' => trim($item['color_code']),
                    'size_code' => trim($item['size_code']),
                    'num' => trim($item['num']),
                    'sku_code' => trim($item['sku_code']),
                    'processing_code' => trim($item['processing_code']),
                    'factory_name' => trim($item['factory_name']),
                    'supplier_id' => $factoryObj['supplier_id'],
                    'bunum' => $item['num']+ceil($item['num']*0.05),//默认溢装比为50%,
                    'createtime' => $createTime,
                    'factory_contract_no' => trim($item['factory_contract_no']),
                    'countnum' => trim($item['countnum']),
                    'countprice' => trim($item['countprice']),
                    'advance_charge' => trim($item['advance_charge']),
                    'embroidery_price' => trim($item['embroidery_price']),
                    'contract_date' => trim($item['contract_date']),
                    'production_date' => trim($item['production_date']),
                    'merchandiser' => trim($item['merchandiser']),
                    'order_processor' => trim($item['order_processor']),
                    'adduser' => trim($item['adduser']),
                    'embroidery_factory' => trim($item['embroidery_factory']),
                    'printing_factory' => trim($item['printing_factory']),
                    'bronzing_factory' => trim($item['bronzing_factory']),
                    'gold_printing_factory' => trim($item['gold_printing_factory']),
                    'unit_price' => trim($item['unit_price']),
                    'add_date' => trim($item['add_date']),
                    'tb_time' => $createTime,
                    'verify_price_number' => trim($item['verify_price_number']), //大货核价编码
                    'export_order_number' => trim($item['export_order_number']), //运营订单编码
                    'source_type' => 1,
                    'is_create' => 0,
                    's_status' => 1,
                    "brand_name" => $brandName,
                    "brand_code" => $brandCode
                ];
                (new SsyProcessingListTable())->createData($data);
            }else{
                $data = [
                    'num' => trim($item['num']),
                    'factory_name' => trim($item['factory_name']),
                    'supplier_id' => $factoryObj['supplier_id'],
                    'factory_contract_no' => trim($item['factory_contract_no']),
                    'countnum' => trim($item['countnum']),
                    'countprice' => trim($item['countprice']),
                    'advance_charge' => trim($item['advance_charge']),
                    'embroidery_price' => trim($item['embroidery_price']),
                    'contract_date' => trim($item['contract_date']),
                    'production_date' => trim($item['production_date']),
                    'merchandiser' => trim($item['merchandiser']),
                    'order_processor' => trim($item['order_processor']),
                    'adduser' => trim($item['adduser']),
                    'embroidery_factory' => trim($item['embroidery_factory']),
                    'printing_factory' => trim($item['printing_factory']),
                    'bronzing_factory' => trim($item['bronzing_factory']),
                    'gold_printing_factory' => trim($item['gold_printing_factory']),
                    'unit_price' => trim($item['unit_price']),
                    'add_date' => trim($item['add_date']),
                    'source_type' => 1,
                    'tb_time' => date("Y-m-d H:i:s"),
                    's_status' => 1,
                    'verify_price_number' => trim($item['verify_price_number']), //大货核价编码
                    'export_order_number' => trim($item['export_order_number']), //运营订单编码
                    "updatetime"=>date('Y-m-d H:i:s')
                ];
                (new SsyProcessingListTable())->updateData($processingObj->id, $data);
                //查看唯一码已生成且工厂名有更新替换 需更新唯一码的加工厂信息
                if($processingObj->is_create){
                    $whereParam = [
                        'processing_code' => $item['processing_code'],
                        'sku_code' => $item['sku_code']
                    ];
                    (new SsyProcessingListDetailsTable())->updateDataWhere($whereParam, [
                        'factory_name' => trim($item['factory_name']),
                        'supplier_id' => $factoryObj['supplier_id'],
                    ]);
                }
            }
        }
        return ['code' => 0, 'msg' => '操作成功'];
    }

    //同步大货核价单
    public function addPricingOrder($pricingNumber)
    {
        $res = SzdptechRepository::searchVerifyPrice(['大货核价'], [$pricingNumber]);
        if(!isset($res['value'][0])){
            return ['code' => -1, 'msg' => '未搜索到大货核价信息'];
        }
        $param = $res['value'][0];
        $exist = (new SsyPricingOrderTable())->where('pricing_number', $pricingNumber)->where('type_no', $param['style_number'])->exists();
        if($exist){
            return ['code' => 0, 'msg' => '大货核价已存在'];
        }
        try{
            $data = [
                "pricing_number" => $param['number'],
                "type_no" => $param['style_number'],
                "type_name" => $param['style'],
                "valuation_purpose" => $param['t73'],//核价用途  大货核价 过审核价 成本预估价 实付核价
                "s_status" => $param['state'],//状态 0.正常 1.锁定
                "product_category" => $param['product_category'] ?? "",//品类
                "style_detail_category" => $param['style_detail_category'] ?? "",//设计分类
                "factory_name" => $param['supplier'] ?? "",
                "currency_id" => $param['currency_id'] ?? "",//币种 1 人民币 2 美元
                "embroidery_factory" => $param['f8'] ?? "",//绣花厂
                "main_material_total" => $param['f69'] ?? "",//主料总价
                "accessories_total" => $param['f70'] ?? "",//辅料总价
                "packing_material_total" => $param['f71'] ?? "",//包材总价
                "process_cost_total" => $param['f72'] ?? "",//加工费总价
                "embroider_total" => $param['f77'] ?? "",//绣花费总价
                "estimate_total" => $param['f78'] ?? "",//预估总价
                "embroider_cost_total" => $param['f62'] ?? "",//绣花成本总价（绣花厂）
                "embroider_cost_plus_total" => $param['f63'] ?? "",//绣花成本加价总价（绣花厂含税价）
                "management_rate" => $param['f61'] ?? "",//管理费率
                "garment_cost_total" => $param['f64'] ?? "",//成衣成本总价（加工厂）
                "garment_cost_plus_total" => $param['f65'] ?? "",//成衣成本加价总价（加工厂含税价）
                "cost_total" => $param['f66'] ?? "",//成本总价
                "cost_plus_total" => $param['f67'] ?? "",//成本加价总价 (总价)
                "orther_total" => $param['f74'] ?? "",//其他费用总价
                "orther_plus_total" => $param['f75'] ?? "",//其他费用加价总价
                "addtime" => $param['creation_time'] ?? "",
                "adduser" => $param['creator'] ?? "",
                "comment" => $param['comment'] ?? "",
                "colour" => $param['colour'] ?? "",
                "createtime" => date("Y-m-d H:i:s")
            ];
            return (new SsyPricingOrderTable())->createData($data);
        }catch (\Exception $e){
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    //同步合同信息
    public function addPricingContract($factoryObj, $param)
    {
        list($factoryContractNo, $typeNo, $contractDate, $orderProcessor) = [$param['factory_contract_no'], $param['type_no'],
            $param['contract_date'], $param['order_processor']];
        $contractObj = (new SsyPricingContractTable())->where('factory_contract_no', $factoryContractNo)->first();
        if(!empty($contractObj)){
            if($contractObj->factory_name != $factoryObj['factory_name']){
                return ['code' => -1, 'msg' => '合同号已存在，且签约工厂名不一致'];
            }
            if(in_array($contractObj->status, [1, 2]) || in_array($contractObj->b_status, [0, 1])){
                return ['code' => -1, 'msg' => '合同已在审批流程中, 请更换合同号再提交'];
            }
            return ['code' => 0, 'msg' => '合同已存在'];
        }else{
            $data = [
                "factory_name" => $factoryObj['factory_name'],
                "factory_contract_no" => $factoryContractNo,
                "contract_date" => $contractDate,
                "order_processor" => $orderProcessor,
                "createtime" => date("Y-m-d H:i:s"),
                "supplier_id" => $factoryObj['supplier_id'],
                "source_factory_groups_id" => $factoryObj["source_factory_groups_id"]
            ];
            return (new SsyPricingContractTable())->createData($data);
        }
    }
}
